<script lang="ts" setup>
import { XtxRegionPickerInstance } from '@/types/component';
import { SwitchOnChange } from '@uni-helper/uni-app-types';
import { ref } from 'vue';
import { getAddressByIdAPI, postAddressAPI, putAddressByIdAPI } from '@/apis/address';
import { onLoad } from '@dcloudio/uni-app';
import { UniFormsInstance } from '@uni-helper/uni-ui-types';

const props = defineProps<{ id?: string }>();

// 根据路由参数判断当前功能
uni.setNavigationBarTitle({ title: props.id ? '修改地址' : '新增地址' });

// 表单验证规则
const rules: UniHelper.UniFormsRules = {
  receiver: {
    rules: [{ required: true, errorMessage: '请输入收货人姓名' }],
  },
  contact: {
    rules: [
      { required: true, errorMessage: '请输入联系方式' },
      { pattern: /^1[3-9]\d{9}$/, errorMessage: '手机号格式不正确' },
    ],
  },
  fullLocation: {
    rules: [{ required: true, errorMessage: '请选择所在地区' }],
  },
  address: {
    rules: [{ required: true, errorMessage: '请选择详细地址' }],
  },
};

// 表单实例
const formRef = ref<UniFormsInstance>();

// 地址表单数据
const formData = ref({
  receiver: '',
  contact: '',
  fullLocation: '',
  address: '',
  isDefault: 0,
});
const getAddressById = async (id: string) => {
  const response = await getAddressByIdAPI(id).request;
  const { receiver, contact, fullLocation, address, isDefault } = response.result;
  formData.value = { receiver, contact, fullLocation, address, isDefault };
};

// 地址选择器实例
const regionPickerRef = ref<XtxRegionPickerInstance>();

// 地区选择器变化事件
const onRegionChange = (value: string) => formData.value.fullLocation = value;

// 默认设置变化
const onDefaultChange: SwitchOnChange = ({ detail: { value } }) => formData.value.isDefault = +value;

// 提交事件
const submit = async () => {
  try {
    // 验证表单
    await formRef.value?.validate?.();
    const { provinceCode, cityCode, countyCode } = regionPickerRef.value;
    const data = { ...formData.value, provinceCode, cityCode, countyCode };
    await (props.id ? putAddressByIdAPI(props.id, data) : postAddressAPI(data)).request;
    // 完成处理
    uni.navigateBack({ complete: () => uni.showToast({ icon: 'success', title: '编辑成功！' }) });
  }
  catch (e) {
    uni.showToast({ icon: 'none', title: '请填写完整的地址！' });
  }
};

onLoad(() => {
  if (props.id) getAddressById(props.id);
});
</script>

<template>
  <view class="viewport">
    <view class="content">
      <uni-forms :rules="rules" ref="formRef" :model="formData">
        <!-- 表单内容 -->
        <uni-forms-item class="form-item" name="receiver">
          <text class="label">收货人姓名</text>
          <input class="input" v-model="formData.receiver" placeholder="请填写收货人姓名" />
        </uni-forms-item>
        <uni-forms-item class="form-item" name="contact">
          <text class="label">联系方式</text>
          <input class="input" v-model="formData.contact" placeholder="请填写联系方式" />
        </uni-forms-item>
        <uni-forms-item class="form-item" name="fullLocation">
          <text class="label">所在地区</text>
          <XtxRegionPicker ref="regionPickerRef" class="picker" :fullLocation="formData.fullLocation"
            @change="onRegionChange">
            <view class="placeholder">{{ formData.fullLocation || '请选择所在地区' }}</view>
          </XtxRegionPicker>
        </uni-forms-item>
        <uni-forms-item class="form-item" name="address">
          <text class="label">详细地址</text>
          <input class="input" v-model="formData.address" placeholder="街道、楼号、门牌号等信息" />
        </uni-forms-item>
        <view class="form-item">
          <text class="label">设为默认</text>
          <switch class="switch" color="#27ba9b" :checked="!!formData.isDefault" @change="onDefaultChange" />
        </view>
      </uni-forms>
    </view>
    <!-- 提交 -->
    <button class="button" @tap="submit">保存</button>
  </view>
</template>

<style lang="scss">
.viewport {
  width: 100vw;
  height: 100vh;
  background-color: #f4f4f4;
  display: flex;
  flex-direction: column;
}

.content {
  margin: 20rpx 20rpx 0;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .form-item,
  .uni-forms-item {
    margin-bottom: 0;
    position: relative;
    min-height: 96rpx;
    background-color: #fff;
    border-bottom: 1rpx solid #ddd;
    font-size: 28rpx;
    padding: 10rpx;
    display: flex;
    align-items: center;

    .uni-forms-item__content {
      display: flex;
      align-items: center;
    }

    .uni-forms-item__error {
      margin-left: 200rpx;
      transform: translateY(-50%);
    }

    &:last-child {
      border: none;
    }
  }

  .label {
    width: 200rpx;
    color: #333;
  }

  .input {
    flex: 1;
    display: block;
    height: 46rpx;
  }

  .switch {
    position: absolute;
    right: 20rpx;
    transform: scale(0.8);
  }

  .picker {
    flex: 1;
  }

  .placeholder {
    color: #808080;
  }
}

.button {
  margin: 30rpx 20rpx;
  height: 80rpx;
  background-color: #27ba9b;
  border-radius: 80rpx;
  color: #fff;
  font-size: 30rpx;
}
</style>